import { Avatar, ListItemAvatar } from '@material-ui/core';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import { makeStyles } from '@material-ui/core/styles';
import FolderIcon from '@material-ui/icons/Folder';
import ImageIcon from '@material-ui/icons/Image';
import VideoCallIcon from '@material-ui/icons/VideoCall';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router';
import { FixedSizeList, ListChildComponentProps } from 'react-window';
import { useDirectory } from '../context';
import { ListItemType } from '../pages/Home';
import { http, stringifySize } from '../util';
import { ErrorDialog } from './ErrorDialog';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    backgroundColor: theme.palette.background.paper,
  },
}));

interface VirtualizedListProp {
  keyword: string;
  listData: ListItemType[];
  setListData: (listData: ListItemType[]) => void;
}

export function VirtualizedList({ keyword, listData, setListData }: VirtualizedListProp) {
  const classes = useStyles();
  const history = useHistory();
  const { directory, setDirectory } = useDirectory();
  const [isError, setIsError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  useEffect(() => {
    http('list', { data: { directory: directory.join('\\') } })
      .then(data => {
        setListData(data.data);
      })
      .catch(e => {
        setIsError(true);
        setErrorMessage(e.message);
      });
  }, [directory, setListData]);

  const handleFolder = (folderName: string) => {
    setDirectory([...directory, folderName]);
    setListData([]);
  };

  const renderItem = ({ index, style }: ListChildComponentProps) => {
    if (listData[index].type === 'DIRECTORY' && listData[index].name.includes(keyword)) {
      return (
        <ListItem
          style={style}
          key={listData[index].name + index}
          button
          onClick={() => handleFolder(listData[index].name)}
        >
          <ListItemAvatar>
            <Avatar style={{ color: '#f3d16d', backgroundColor: 'white' }}>
              <FolderIcon fontSize="large" />
            </Avatar>
          </ListItemAvatar>
          <ListItemText
            primary={listData[index].name}
            secondary={dayjs(listData[index].lastModified).format('YYYY年MM月DD日 HH:mm:ss')}
          />
        </ListItem>
      );
    } else if (listData[index].type === 'VIDEO' && listData[index].name.includes(keyword)) {
      return (
        <ListItem
          style={style}
          key={listData[index].name + index}
          button
          onClick={() => history.push(`/video/${listData[index].name}`)}
        >
          <ListItemAvatar>
            <Avatar style={{ color: '#f55385', backgroundColor: 'white' }}>
              <VideoCallIcon fontSize="large" />
            </Avatar>
          </ListItemAvatar>
          <ListItemText
            primary={listData[index].name}
            secondary={`${stringifySize(listData[index].size)} | ${dayjs(listData[index].lastModified).format('YYYY年MM月DD日 HH:mm:ss')}`}
          />
        </ListItem>
      );
    } else if (listData[index].type === 'IMAGE' && listData[index].name.includes(keyword)) {
      return (
        <ListItem
          style={style}
          key={listData[index].name + index}
          button
          onClick={() => {
            window.scrollTo(0, 0);
            history.push(`/image?directory=${directory.join('\\')}&index=${index}`)
          }}
        >
          <ListItemAvatar>
            <Avatar style={{ color: '#a074c4', backgroundColor: 'white' }}>
              <ImageIcon fontSize="large" />
            </Avatar>
          </ListItemAvatar>
          <ListItemText
            primary={listData[index].name}
            secondary={`${stringifySize(listData[index].size)} | ${dayjs(listData[index].lastModified).format('YYYY年MM月DD日 HH:mm:ss')}`}
          />
        </ListItem>
      );
    }
    return null;
  };
  return (
    <>
      <div className={classes.root}>
        <FixedSizeList
          height={window.innerHeight}
          width="100%"
          itemSize={70}
          itemCount={listData.filter(item => item.name.includes(keyword)).length}
        >
          {renderItem}
        </FixedSizeList>
      </div>
      <ErrorDialog isError={isError} setIsError={setIsError} message={errorMessage} />
    </>
  );
}
